package com.bigdata.schaduler.service;

import com.bigdata.schaduler.client.DolphinClient;
import com.bigdata.schaduler.util.PageInfo;
import org.apache.dolphinscheduler.common.enums.HttpMethod;
import org.apache.dolphinscheduler.dao.entity.WorkerGroup;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.List;
import java.util.Optional;

public class WorkerGroupService {

  private final DolphinClient dolphinClient;

  public WorkerGroupService(DolphinClient dolphinClient) {
    this.dolphinClient = dolphinClient;
  }

  public String getWorkGroupUri() {
    return "/worker-groups";
  }

  public PageInfo<WorkerGroup> selectPageList(String searchVal, Integer pageNo, Integer pageSize) {
    String uri = getWorkGroupUri();
    pageNo = Optional.ofNullable(pageNo).orElse(1);
    pageSize = Optional.ofNullable(pageSize).orElse(10);

    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("pageNo", pageNo);
    params.add("pageSize", pageSize);
    params.add("searchVal", searchVal);
    return dolphinClient.requestFormData(HttpMethod.GET, uri, params, PageInfo.class);
  }

  public void save(Integer id, String name, String addrList) {
    String uri = getWorkGroupUri();

    MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
    paramMap.add("id", id);
    paramMap.add("name", name);
    paramMap.add("addrList", addrList);

    dolphinClient.requestFormData(HttpMethod.POST, uri, paramMap, Void.class);
  }

  public void delete(Integer id) {
    String uri = getWorkGroupUri() + "/worker-groups/" + id;
    dolphinClient.requestFormData(HttpMethod.DELETE, uri, null, Void.class);
  }

  public List<String> queryWorkerGroupList() {
    String uri = getWorkGroupUri() + "/worker-groups/worker-address-list";
    return dolphinClient.requestFormData(HttpMethod.GET, uri, null, List.class);
  }

  public List<String> queryAllWorkerGroups() {
    String uri = getWorkGroupUri() + "/worker-groups/all";
    return dolphinClient.requestFormData(HttpMethod.GET, uri, null, List.class);
  }

}
